package com.hxd.otc.module.convenience.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.hxd.otc.R;
import com.hxd.otc.base.BaseDialogFragment;
import com.hxd.otc.base.BaseFragment;
import com.hxd.otc.common.UserHelper;
import com.hxd.otc.common.enums.ExValidType;
import com.hxd.otc.module.convenience.activity.OilRechargeFailActivity;
import com.hxd.otc.module.convenience.bean.OrderFinishedBean;
import com.hxd.otc.module.convenience.bean.OrderInfoBean;
import com.hxd.otc.module.convenience.bean.PaymentMethodBean;
import com.hxd.otc.module.convenience.contract.PayPanelContract;
import com.hxd.otc.module.convenience.presenter.PayPanelPresenter;
import com.hxd.otc.module.wallet.bean.WalletCurrencyBean;
import com.hxd.otc.utils.ResourceUtil;
import com.hxd.otc.utils.StringUtil;
import com.hxd.otc.utils.UIUtils;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;

/**
 * Created by lzy on 2018/12/12 0012.
 * description ${支付对话框-支付面板}
 */
public class PayPanelFragment extends BaseFragment<PayPanelPresenter> implements PayPanelContract.IView, View.OnClickListener {
    private static final int REQUEST_CODE_PAYMENT_METHOD = 2001;
    @BindView(R.id.tv_money)
    TextView mTvMoney;
    @BindView(R.id.tv_money_unit)
    TextView mTvMoneyUnit;
    @BindView(R.id.tv_order_info)
    TextView mTvOrderInfo;
    @BindView(R.id.tv_payment_method)
    TextView mTvPaymentMethod;
    @BindView(R.id.tv_immediate_payment)
    TextView mTvImmediatePayment;
    @BindView(R.id.et_auth_code)
    EditText mEtAuthCode;
    @BindView(R.id.tv_get_auth_code)
    TextView mTvGetAuthCode;

    public static final String EXTRA_ORDER_INFO = "order_info";
    OrderInfoBean orderInfoBean;
    private Disposable mDisposable;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_pay_panel;
    }

    @Override
    protected PayPanelPresenter createPresenter() {
        return new PayPanelPresenter(this);
    }

    @Override
    protected void initView() {
        Bundle arguments = getArguments();
        if (arguments == null)
            throw new RuntimeException(getString(R.string.failed_to_get_order_information));
        orderInfoBean = (OrderInfoBean) arguments.getSerializable(EXTRA_ORDER_INFO);
        if (orderInfoBean == null)
            throw new RuntimeException(getString(R.string.failed_to_get_order_information));

        mPresenter.initOrderInfo(orderInfoBean);
        mTvOrderInfo.setText(orderInfoBean.getGoodsName());
        updatePaymentMethodUI(orderInfoBean, null);

        //修改验证码提示文案
        ExValidType exValidType = UserHelper.getExValidType();
        mEtAuthCode.setText("");
        if (ExValidType.GoogleAuth.equals(exValidType)) {
            mEtAuthCode.setHint(R.string.please_input_your_google_code);
            UIUtils.setGoogleCodeEditText(mEtAuthCode);
            mTvGetAuthCode.setVisibility(View.GONE);
        } else if (ExValidType.SMS.equals(exValidType)) {
            mEtAuthCode.setHint(R.string.please_input_your_phone_ver_code);
            UIUtils.setPhoneVerCodeEditText(mEtAuthCode);
            mTvGetAuthCode.setVisibility(View.VISIBLE);
        } else if (ExValidType.Email.equals(exValidType)) {
            mEtAuthCode.setHint(R.string.please_input_your_email_ver_code);
            UIUtils.setEmailVerCodeEditText(mEtAuthCode);
            mTvGetAuthCode.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void initData() {
        mPresenter.requestWalletInfo();
    }

    @Override
    protected void initEvent() {
    }

    @OnClick({R.id.tv_immediate_payment, R.id.tv_payment_method, R.id.iv_close, R.id.tv_get_auth_code})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_immediate_payment://立即支付
                onImmediatePayment();
                break;
            case R.id.tv_payment_method://选择支付方式
                onPaymentMethod();
                break;
            case R.id.iv_close:
                UIUtils.dismissDialogFragment(((PayDialogFragment) getParentFragment()));
                break;
            case R.id.tv_get_auth_code://获取验证码
                onSendAuthCode();
                break;
        }
    }

    private void onSendAuthCode() {
        ExValidType exValidType = UserHelper.getExValidType();
        if (ExValidType.SMS.equals(exValidType)) {
            mPresenter.sendPhoneSms();
        } else if (ExValidType.Email.equals(exValidType)) {
            mPresenter.sendEmailVerCode();
        }
    }

    /**
     * 选择支付方式
     */
    private void onPaymentMethod() {
        Fragment parentFragment = getParentFragment();
        if (parentFragment != null) {
            PaymentMethodFragment paymentMethodFragment = new PaymentMethodFragment();
            paymentMethodFragment.setTargetFragment(this, REQUEST_CODE_PAYMENT_METHOD);
            ((BaseDialogFragment) parentFragment).addChildFragment(R.id.fl_container_pay, paymentMethodFragment, PaymentMethodFragment.class.getSimpleName());
        }
    }

    /**
     * 立即支付
     */
    private void onImmediatePayment() {
        String authCode = mEtAuthCode.getText().toString().trim();
        if (TextUtils.isEmpty(authCode)) {
            showToast(mEtAuthCode.getHint().toString());
            return;
        }
        mTvImmediatePayment.setOnClickListener(null);
        mPresenter.pay(authCode);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_PAYMENT_METHOD && resultCode == Activity.RESULT_OK && data != null) {
            PaymentMethodBean paymentMethodBean = (PaymentMethodBean) data.getSerializableExtra(PaymentMethodFragment.RESULT_EXTRA_PAYMENT_METHOD);
            //更新支付方式,不应直接更新，而应进行对应币种实际支付价格查询之后才更新选中的币种
            mPresenter.getRate(paymentMethodBean.getSymbol());
        }
    }

    @Override
    public void getRateSuccess(String newSymbol, String newVolume) {
        mPresenter.updateNewPaymentMethod(newSymbol, newVolume);
        updatePaymentMethodUI(mPresenter.getOrderInfoBean(), mPresenter.getCurCoinWalletInfo());
    }

    @Override
    public void sendCodeSuccess(String successMsg) {
        showToast(successMsg);
        startCountdown();
    }

    private void startCountdown() {
        mTvGetAuthCode.setEnabled(false);
        //从0开始发射11个数字为：0-10依次输出，延时0s执行，每1s发射一次。
        mDisposable = Flowable.intervalRange(0, 60, 0, 1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(new io.reactivex.functions.Consumer<Long>() {
                    @SuppressLint("DefaultLocale")
                    @Override
                    public void accept(Long aLong) throws Exception {
                        if (mTvGetAuthCode == null) return;
                        mTvGetAuthCode.setText(String.format("%ds", 60 - aLong));
                    }
                })
                .doOnComplete(new Action() {
                    @Override
                    public void run() throws Exception {
                        if (mTvGetAuthCode == null) return;
                        //倒计时完毕置为可点击状态
                        mTvGetAuthCode.setEnabled(true);
                        mTvGetAuthCode.setText(R.string.send_message_code);
                    }
                })
                .subscribe();
    }

    public static PayPanelFragment getInstance(OrderInfoBean orderInfoBean) {
        PayPanelFragment payPanelFragment = new PayPanelFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(EXTRA_ORDER_INFO, orderInfoBean);
        payPanelFragment.setArguments(bundle);
        return payPanelFragment;
    }

    @Override
    public void paySuccess(OrderFinishedBean orderFinishedBean) {
        UIUtils.dismissDialogFragment(((PayDialogFragment) getParentFragment()));
        mTvImmediatePayment.setOnClickListener(this);
        Bundle bundle = new Bundle();
        bundle.putInt("code", 100000);
        bundle.putSerializable("orderInfoBean", orderInfoBean);
        bundle.putSerializable("orderFinishedBean", orderFinishedBean);
        $startActivity(OilRechargeFailActivity.class, bundle);
    }

    @Override
    public void payFail(int errType, String errMessage) {
        UIUtils.dismissDialogFragment(((PayDialogFragment) getParentFragment()));
        showToast(errMessage);
        mTvImmediatePayment.setOnClickListener(this);
        if (errType == 20000001) {////参数错误
            return;
        }
        switch (errType) {
            case 20000002://  //充值失败
            case 20000007://  //扣币失败
            case 20000003://扣币中
            case 20000004://扣费中
            case 20000005:  //充值中
                Bundle bundle = new Bundle();
                bundle.putSerializable("orderInfoBean", orderInfoBean);
                bundle.putInt("code", errType);
                $startActivity(OilRechargeFailActivity.class, bundle);
                break;
        }
    }

    /**
     * 获取钱包信息成功
     */
    @Override
    public void getWalletInfoSuccess() {
        updatePaymentMethodUI(mPresenter.getOrderInfoBean(), mPresenter.getCurCoinWalletInfo());
    }

    /**
     * 更新付款方式ui
     *
     * @param orderInfoBean
     * @param currencyBean
     */
    private void updatePaymentMethodUI(OrderInfoBean orderInfoBean, WalletCurrencyBean currencyBean) {
        mTvMoneyUnit.setText(orderInfoBean.getRealSymbol());
        mTvMoney.setText(String.format("%s", orderInfoBean.getVolume()));
        if (currencyBean == null) {
            //当获取钱包信息失败，不进行拦截，交给服务端校验
            mTvPaymentMethod.setText(ResourceUtil.getString(R.string.sub_payment, orderInfoBean.getRealSymbol()));
            mTvImmediatePayment.setEnabled(true);
            return;
        }

        //判断余额是否足够
        double volume = orderInfoBean.getVolume();//订单中的虚拟币数量
        double availableVolume = currencyBean.volume;//可用资产
        if (availableVolume < volume) {//该币种余额不足
            //EUC支付(余0.1234，余额不足)
            String paymentMethod = ResourceUtil.getString(R.string.sub_payment, orderInfoBean.getRealSymbol());
            String balanceWarn = ResourceUtil.getString(R.string.balance_warn_template, StringUtil.handleZero(availableVolume + ""));

            SpannableStringBuilder style = new SpannableStringBuilder(paymentMethod).append(balanceWarn);
            style.setSpan(new ForegroundColorSpan(ResourceUtil.getColor(R.color.color_FF464E5F)), 0, paymentMethod.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            style.setSpan(new ForegroundColorSpan(Color.RED), paymentMethod.length(), style.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            mTvPaymentMethod.setText(style);
            //余额不足则禁止支付
            mTvImmediatePayment.setEnabled(false);
        } else {
            mTvPaymentMethod.setText(ResourceUtil.getString(R.string.sub_payment, orderInfoBean.getRealSymbol()));
            //允许支付
            mTvImmediatePayment.setEnabled(true);
        }
    }

    @Override
    public void onDestroy() {
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
            mDisposable = null;
        }
        super.onDestroy();
    }
}
